<template>
    <!-- 入职审批 -->
    <div>
        <el-row :gutter="24">
            <el-col :span="2">
                <div class="grid-content ep-bg-purple">
                    <el-button type="primary" plain @click="add" style="width: 100px;"><el-icon>
                            <Plus />
                        </el-icon>添加</el-button>
                </div>
            </el-col>

            <el-col :span="1.5">
                <el-button type="primary" plain style="border: none;  ">
                    导入
                    <i class="el-icon-upload el-icon--right"></i>
                </el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button type="primary" plain style="border: none; ">
                    导出
                    <i class="el-icon-upload el-icon--right"></i>
                </el-button>
            </el-col>
            <el-col :span="2">
                <div class="grid-content ep-bg-purple">
                <el-button type="success" plain @click="approveSelected" style="width: 100px;">
                    <el-icon><Check /></el-icon>审核
                </el-button>
                </div>
            </el-col>

            <el-col :span="2">
                <div class="grid-content ep-bg-purple">
                </div>
            </el-col>


            <el-col :span="8">
                <div class="grid-content ep-bg-purple">
                </div>
            </el-col>


            <el-col :span="4">
                <div class="grid-content ep-bg-purple-light"> <el-input style="width: 180px" size="large"
                        placeholder="搜索">
                        <template #prefix><el-icon class="el-input__icon">
                                <search />
                            </el-icon></template></el-input>
                </div>
            </el-col>

            <el-col :span="1">
                <div class="grid-content ep-bg-purple-light">
                    <a-tooltip content="筛选" position="bottom" background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click="dialog = true"><el-icon>
                                <Filter />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>

            <el-col :span="1">
                <div class="grid-content ep-bg-purple-light"> <a-tooltip content="排序" position="bottom"
                        background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click=""><el-icon>
                                <Sort />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>
            <el-col :span="2">
            <div class="grid-content ep-bg-purple-light">
                <a-tooltip content="刷新" position="bottom" background-color="rgb(52, 145, 250)" mini>
                <el-button size="default" @click="getPage">
                    <el-icon><Refresh /></el-icon>
                </el-button>
                </a-tooltip>
            </div>
            </el-col>
        </el-row>
        <el-table :data="page.records " border ref="multipleTable" tooltip-effect="dark" style="width: 100%; "
            @cell-dblclick="handleClick">

            <el-table-column type="selection" label="选择" fixed="left" width="50" />
            <el-table-column fixed="left" prop="CandidateID" label="标题" width="150" />
            <el-table-column v-for="col in columns" :prop="col.id" :key="col.id" :label="col.label" :width="col.width">
            <template #default="scoped">
            <!-- 工号列特殊处理 -->
            <span v-if="col.id === 'employeeIdNumber'">
                {{ scoped.row.employeeIdNumber || '无工号' }}
            </span>
            
            <!-- 密码列特殊处理 -->
            <span v-else-if="col.id === 'loginPassword'">
                <el-tag v-if="scoped.row.loginPassword" type="info">******</el-tag>
                <el-tag v-else type="warning">未设置</el-tag>
            </span>
            
            <!-- 户籍类型为蓝色背景白色文字 -->
            <el-button v-else-if="col.id === 'householdRegistration' && scoped.row.householdRegistration"
                :style="{ backgroundColor: '#409EFF', borderColor: '#409EFF', color: '#FFFFFF' }" disabled>
                {{ scoped.row.householdRegistration }}
            </el-button>
            
            <!-- 婚姻状态为绿色背景白色文字 -->
            <el-button v-else-if="col.id === 'maritalStatus' && scoped.row.maritalStatus"
                :style="{ backgroundColor: '#67C23A', borderColor: '#67C23A', color: '#FFFFFF' }" disabled>
                {{ scoped.row.maritalStatus }}
            </el-button>
            
            <el-tag v-else-if="col.id === 'approvalStatus'" 
                :type="scoped.row.approvalStatus === '已审核' ? 'success' : 'info'">
                {{ scoped.row.approvalStatus || '未审核' }}
            </el-tag>
            
            <!-- 聘用形式为红色背景白色文字 -->
            <el-button v-else-if="col.id === 'employmentForm' && scoped.row.employmentForm"
                :style="{ backgroundColor: '#F56C6C', borderColor: '#F56C6C', color: '#FFFFFF' }" disabled>
                {{ scoped.row.employmentForm }}
            </el-button>
            
            <!-- HR确认为红色背景白色文字 -->
            <el-button v-else-if="col.id === 'hrConfirm' && scoped.row.hrConfirm"
                :style="{ backgroundColor: '#F56C6C', borderColor: '#F56C6C', color: '#FFFFFF' }" disabled>
                {{ scoped.row.hrConfirm }}
            </el-button>
            
            <!-- 其他情况正常显示文本 -->
            <span v-else>{{ scoped.row[col.id] }}</span>
            </template>
  </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="page.current" v-model:page-size="page.size" :page-sizes="[1, 2, 3, 4]"
            :disabled="disabled" layout="total, sizes, prev, pager, next, jumper" :total="page.total" @current-change="handleCurrentChange">
        </el-pagination>
    </div>
    <!-- 详情页面 -->
    <el-dialog 
        title="详细信息" 
        v-model="isVisible" 
        fullscreen 
        destroy-on-close
        @close="handleDialogClose">
        <hr />
        <DetailsOfTheTalent 
        :userId="selectedUserId" 
        @close-detail="handleCloseDetail"
        @refresh-data="handleRefreshData">
        </DetailsOfTheTalent>
    </el-dialog>

    <!--筛选  -->
    <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
        <div class="demo-drawer__content">
            <el-form :model="form" style="height: 600px;">
                <el-select v-model="Screening" placeholder="筛选" style="width: 360px" placement="bottom">
                    <template #label="{ label, value }">
                        <span style="font-weight: bold">{{ label }}</span>
                    </template>
                    <el-option v-for="item in FilterData" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

            </el-form>
            <div class="demo-drawer__footer">
                <el-button @click="cancelForm">取消</el-button>
                <el-button type="primary" :loading="loading" @click="onClick">
                    {{ loading ? '提交中 ...' : '提交' }}
                </el-button>
            </div>
        </div>
    </el-drawer>
    <el-dialog title="添加" v-model="AddDisplay" fullscreen destroy-on-close>
        <OnboardingAddition></OnboardingAddition>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import request from '@/api/request'
import OnboardingAddition from '@/views/onboarding/onboardingApproval/insert.vue'
import { ElMessage } from 'element-plus'
import DetailsOfTheTalent from '@/views/onboarding/onboardingApproval/detailed.vue'
const isVisible = ref(false)
const selectedUserId = ref(null)
const loading = ref(false)
const dialog = ref(false)


const columns = ref([
    { id: 'approvalStatus', label: '审核状态', width: '120' }, 
    { id: 'employeeId', label: '编号', width: '200' },
    { id: 'employeeIdNumber', label: '工号', width: '150' }, 
    { id: 'loginPassword', label: '密码', width: '150' },   
    { id: 'employeeName', label: '姓名', width: '200' },
    // { id: 'employeeNumber', label: '身份证号', width: '200' },
    { id: 'employeeAge', label: '性别', width: '120' },
    { id: 'employeeBirthdate', label: '出生日期', width: '200' },
    { id: 'employeePhone', label: '手机号', width: '200' },
    { id: 'householdRegistration', label: '户籍类型', width: '200' },
    { id: 'origin', label: '籍贯', width: '200' },
    { id: 'ethnicGroup', label: '民族', width: '200' },
    { id: 'placeHouseholdRegistration', label: '户籍所在地', width: '200' },
    { id: 'politicalAppearance', label: '政治面貌', width: '200' },
    { id: 'maritalStatus', label: '婚姻状态', width: '200' },
    { id: 'dateParticipation', label: '参加工作日期', width: '200' },
    { id: 'emergencyContactsName', label: '紧急联系人', width: '200' },
    { id: 'emergencyContactsRelationship', label: '紧急联系人关系', width: '200' },
    { id: 'emergencyContactsPhone', label: '紧急联系人电话', width: '200' },
    { id: 'MarriageAndChildbearing', label: '参保城市', width: '200' },
    { id: 'socialSecurity', label: '社保账户', width: '200' },
    { id: 'RecruiterID', label: '公积金账号', width: '200' },
    { id: 'bankCardNumber', label: '银行卡号', width: '200' },
    { id: 'openAnAccount', label: '开户行', width: '200' },
    { id: 'dateOfInduction', label: '入职日期', width: '200' },
    { id: 'onboardingDepartment', label: '入职部门', width: '200' },
    { id: 'entryPosition', label: '入职岗位', width: '200' },
    { id: 'employmentForm', label: '聘用形式', width: '200' },
    { id: 'whetherProbationPeriod', label: '是否有试用期', width: '200' },
    { id: 'degree', label: '最高学历', width: '200' },
    { id: 'graduatedSchool', label: '毕业院校', width: '200' },
    { id: 'major', label: '所需专业', width: '200' },
    { id: 'graduatedTime', label: '毕业时间', width: '200' },
    { id: 'departmentHead', label: '部门经理', width: '200' },
    { id: 'departmentHeadOpinion', label: '部门主管意见', width: '200' },
    { id: 'employeeStatus', label: '员工状态', width: '200' },
    { id: 'applicationDate', label: '申请时间', width: '200' },
    { id: 'responsibleFoHr', label: '负责HR', width: '200' },
    { id: 'hrConfirm', label: 'HR确认', width: '200' },
])


const form = ref();
const Screening = ref('')
const FilterData = ref([
    { value: '全部', label: '全部' },
    { value: '在职', label: '在职' },
    { value: '待转正', label: '待转正' },
])
const onClick = () => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
        dialog.value = false
    }, 400)
}
const add = () => {
  AddDisplay.value = true;
}
onMounted(() => {
  getPage();
})
const handleCloseDetail = () => {
  isVisible.value = false;
}
const handleRefreshData = () => {
  getPage();
}
const handleDialogClose = () => {
  isVisible.value = false;
}
const multipleTable = ref()
// 更新页面数据中的审核状态
const updatePageData = (updatedRows) => {
  const updatedRecords = [...page.value.records];
  
  updatedRows.forEach(updatedRow => {
    const index = updatedRecords.findIndex(record => 
      (record.employeeId || record.id) === (updatedRow.employeeId || updatedRow.id)
    );
    
    if (index !== -1) {
      updatedRecords[index] = { ...updatedRecords[index], approvalStatus: '已审核' };
    }
  });
  
  // 更新页面数据
  page.value.records = updatedRecords;
}
const cancelForm = () => {
    loading.value = false
    dialog.value = false
}

const handleClick = (row) => {
    console.log(row)
    selectedUserId.value = row.employeeId || row.id
    isVisible.value = true
}
const AddDisplay = ref(false)
//查询分页
const page = ref({
    current: 1,
    size: 4,
    total: 10,
    records: []
})

const disabled = ref(false)
// 分页切换
const handleCurrentChange = (val) => {
    page.value.current = val
    getPage()
}

const Zdata = ref([])
const data = () => {
    request({
        url: 'into/find',
        method: 'get',
        params: {
            ...Zdata.value
        }
    }).then(res => {

        if (res && res.data && res.data !== null) {
            Zdata.value = res.data.records || []
        } else {
            Zdata.value = []
        }
        console.log(Zdata.value)
    }).catch(err => {
        console.error('获取数据失败:', err)
        Zdata.value = []
    })
}
// 审核选中项的方法
const approveSelected = () => {
  const selectedRows = multipleTable.value.getSelectionRows()
  
  if (selectedRows.length === 0) {
    ElMessage.warning('请先选择要审核的数据')
    return
  }
  selectedRows.forEach(row => {
    row.approvalStatus = '已审核'
  })
  
  ElMessage.success(`成功审核 ${selectedRows.length} 条数据`)
  
  // 保存审核状态到本地存储
  saveApprovalStatus(selectedRows);
  
  // 更新页面数据以反映审核状态
  updatePageData(selectedRows);
}

// 保存审核状态到本地存储
const saveApprovalStatus = (approvedRows) => {
  try {
    // 获取现有的审核状态
    const existingStatus = JSON.parse(localStorage.getItem('employeeApprovalStatus') || '{}');
    
    // 更新审核状态
    approvedRows.forEach(row => {
      const id = row.employeeId || row.id;
      if (id) {
        existingStatus[id] = '已审核';
      }
    });
    
    // 保存到本地存储
    localStorage.setItem('employeeApprovalStatus', JSON.stringify(existingStatus));
  } catch (error) {
    console.error('保存审核状态失败:', error);
  }
}

// 从本地存储加载审核状态
const loadApprovalStatus = () => {
  try {
    const approvalStatus = JSON.parse(localStorage.getItem('employeeApprovalStatus') || '{}');
    return approvalStatus;
  } catch (error) {
    console.error('加载审核状态失败:', error);
    return {};
  }
}
//查询分页
const getPage = () => {
  request({
    url: 'into/findPage',
    method: 'get',
    params: {
      pageNum: page.value.current,
      pageSize: page.value.size
    }
  }).then(res => {
    console.log("后端返回原始数据:", res);
    if (res && res.data) {
      page.value = {
        current: res.data.current || page.value.current,
        size: res.data.size || page.value.size,
        total: res.data.total || 0,
        records: res.data.records || []
      };
      
      if (!Array.isArray(page.value.records)) {
        page.value.records = [];
      }
      
      applyLocalApprovalStatus();
    } else {
      page.value.records = [];
    }
    console.log("处理后的页面数据:", page.value);
  }).catch(err => {
    console.error("读取失败", err);
    page.value.records = [];
  })
}

// 应用本地存储的审核状态到页面数据
const applyLocalApprovalStatus = () => {
  if (!page.value.records || !Array.isArray(page.value.records)) {
    return;
  }
  const approvalStatus = loadApprovalStatus();
  
  if (Object.keys(approvalStatus).length > 0) {
    const updatedRecords = [...page.value.records];
    
    updatedRecords.forEach(record => {
      const id = record.employeeId || record.id;
      if (id && approvalStatus[id]) {
        record.approvalStatus = approvalStatus[id];
      }
    });
    
    page.value.records = updatedRecords;
  }
}
data() // 获取数据  
</script>

<style scoped></style>
